package exchange;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;

import message.Message;
import message.MessageType;
import message.Order;

public class ExchangeClient implements Runnable {

	ObjectInputStream in;
	ObjectOutputStream out;
	String clientId;
	private HashMap<String, ExchangeEngine> enginesMap;
	private HashMap<String, ExchangeClient> clientsMap;

	public ObjectOutputStream getOut() {
		return out;
	}

	public ExchangeClient(ObjectInputStream in, ObjectOutputStream out,
			String clientId, HashMap<String, ExchangeEngine> enginesMap, HashMap<String, ExchangeClient> clientsMap) {
		this.in = in;
		this.out = out;
		this.clientId = clientId;
		this.enginesMap = enginesMap;
		this.clientsMap = clientsMap;
		}

	@Override
	public void run() {
		messageReader();
	}

	private void messageReader() {
		System.out.println("ExchangeClient is running");
		boolean isConnectionOpened = true;
		while (isConnectionOpened) {
			String message = "empty";
			try {
				message = (String) in.readObject();
				System.out.println("IN : " + message);

				Parser parser = new Parser();
				//String msgType = parser.takeValue(message, "35");
				String orderID = parser.takeValue(message, "11");
				String symbol = parser.takeValue(message, "55");
				int operation = Integer.parseInt(parser
						.takeValue(message, "54"));
				int qty = Integer.parseInt(parser.takeValue(message, "38"));
				double price = Double.parseDouble(parser.takeValue(message,
						"44"));
				//String ordType = parser.takeValue(message, "40");

				Order o = new Order(clientId, orderID, symbol, operation,
						price, qty);

				if (enginesMap.containsKey(symbol)) {
					enginesMap.get(symbol).inQueue.add(o);
				} else {
					Message outMessage = new Message(o);
					outMessage.setType(MessageType.REJECT);	
					outMessage.setText("Wrong symbol");
					out.writeObject(outMessage.toString());
				}

			} catch (ClassNotFoundException | IOException e) {
				System.out.println("client has closed the connection");
				clientsMap.remove(clientId);
				isConnectionOpened = false;
			}
		}
	}

}
